package info.jafe.common.task;

import java.util.concurrent.ExecutorService;

import info.jafe.common.exception.UnRegisteredException;
import info.jafe.common.task.factory.DefaultThreadPoolFactory;
import info.jafe.common.task.factory.ThreadPoolFactory;
import info.jafe.common.util.PostUtils;

/**
 * Created by jafe chang on 2016/12/30.
 */

public class TaskManager {
    private static TaskManager instance;
    private static ThreadPoolFactory factory;
    private ExecutorService executor;


    private TaskManager() {
    }

    public static void register() {
        register(new DefaultThreadPoolFactory());
    }

    public static void register(ThreadPoolFactory factory) {
        if (factory == null) {
            factory = new DefaultThreadPoolFactory();
        }
        if (TaskManager.factory != null) {
            TaskManager taskManager = getInstance();
            taskManager.executor = null;
        }
        TaskManager.factory = factory;
    }

    private static synchronized TaskManager getInstance() {
        if (instance == null) {
            synchronized (TaskManager.class) {
                instance = new TaskManager();
            }
        }
        return instance;
    }

    public static void execute(ManagedTask managedTask, Object... params) {
        TaskManager taskManager = getInstance();
        if (taskManager.executor == null) {
            if (factory == null) {
//                throw new UnRegisteredException(UnRegisteredException.THREAD_FACTORY_UNRESTERED);
                register();
            }
            taskManager.executor = factory.create();
        }
        managedTask.setParams(params);
        taskManager.executor.execute(managedTask);
    }

    public static void post(Runnable command) {
        PostUtils.run(command);
    }

    public static void post(Runnable command, long delayMillis) {
        PostUtils.run(command, delayMillis);
    }

    public static void postDelayed(Runnable command, long delayMillis) {
        PostUtils.run(command, delayMillis);
    }

}

